"""
#!/usr/bin/env python
# -*- coding:utf-8 -*-
@Project : All_Designer
@File : A_LiveORSnap.py
@Author : RuanYaoHuang
@Time : 2023/3/12 21:17

"""
import os
import sys
import time
import numpy as np

from PyQt5.QtCore import *
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import *
from PyQt5.QtWidgets import QSizePolicy
from PyQt5.QtCore import QThread, pyqtSignal

from arena_api.buffer import *
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas

from Device_Find import Device_Find  # 搜索设备

from ViewImage import ViewThread
from SnapImage import SnapThread
from RGGBImageView import viewOnlyChannelThread



class LiveORSnap(QWidget):
    Initial_signal = pyqtSignal()
    def __init__(self):
        super(LiveORSnap, self).__init__(parent=None)
        # 总布局
        self.allLayout = QHBoxLayout()
        self.setLayout(self.allLayout)
        # 左侧布局
        self.leftLayout = QVBoxLayout()
        # 顶端按钮布局
        self.deviceGroup = QGroupBox("设备")
        self.deviceLayout = QHBoxLayout()
        
        self.connectCameraButton = QPushButton("连接")
        self.openButton = QPushButton("开启流")
        self.closeButton = QPushButton("关闭流")
        self.returnButton = QPushButton("返回")

        # 像素格式
        self.imgGroup = QGroupBox("像素格式")
        self.imgLayout = QGridLayout()
        self.formatLabel = QLabel("格 式:")
        self.formatEdit = QComboBox()
        self.pixelLabel = QLabel("分辨率:")
        self.pixelEdit = QComboBox()
        # 相机参数设置
        self.paramGroup = QGroupBox("相机参数")
        self.paramLayout = QVBoxLayout()

        self.expLayout = QHBoxLayout()
        self.expLabel = QLabel("曝光")
        self.expEdit = QLineEdit()
        self.usLabel = QLabel("(us)")
        self.expTip = QLabel("33.456us~44831.2us")

        self.sliderExpLayout = QHBoxLayout()
        self.sliderExpo = QSlider(Qt.Horizontal)
        self.expCheckButton = QCheckBox("自动")
        # 帧率
        self.fpsLayout = QHBoxLayout()
        self.fpsLabel = QLabel("帧率:")
        self.fpsEdit = QLineEdit()
        self.sliderFpsLayout = QHBoxLayout()
        self.sliderFps = QSlider(Qt.Horizontal)
        self.fpsCheckButton = QCheckBox("自动")
        # 增益
        self.gainLayout = QHBoxLayout()
        self.gainLabel = QLabel("增益:")
        self.gainEdit = QLineEdit()
        self.sliderGainLayout = QHBoxLayout()
        self.sliderGain = QSlider(Qt.Horizontal)
        self.gainCheckButton = QCheckBox("自动")
        # 白平衡
        self.balanceWhiteLayout = QHBoxLayout()
        self.balanceWhiteLabel = QLabel("白平衡:")
        self.balanceWhiteCombox = QComboBox()

        self.buttonLayout = QHBoxLayout()
        self.snapButton = QPushButton("捕获图像")
        self.recorderButton = QPushButton("录制视频")
        self.endButton = QPushButton("停止录制")
        # 图像捕捉
        self.imgSnapGroup = QGroupBox("图像捕捉")
        self.imgSnapLayout = QVBoxLayout()
        self.pathLayout = QHBoxLayout()
        self.pathLabel = QLabel("路径")
        self.pathEdit = QLineEdit()
        self.openFileButton = QPushButton("打开")
        # 限制
        self.limitLayout = QHBoxLayout()
        self.limitLabel = QLabel("限制")
        self.limitEdit = QComboBox()
        self.planeButtonLayout = QHBoxLayout()
        self.planeButton = QPushButton("计划拍摄")
        self.planeStopButton = QPushButton("停止捕获")
        # GroupBox-》控件及布局
        self.groupBox = QGroupBox("预览")
        self.gropboxlayouth = QVBoxLayout()
        self.tips = QLabel("👈视频|图片👉")
        self.groupLayout = QGridLayout()
        self.viewLabel = QLabel()
        self.linewidget = QLineEdit()
        self.fig1 = Figure()
        self.view_RGGB = FigureCanvas(self.fig1)
        self.chooseDir = QLineEdit()
        self.chooseRaw = QPushButton("选择")

        # 定义变量
        self.raw_image = None
        # 当前路径
        self.currentPath = QDir.currentPath()
        self.cur_path_str = self.currentPath.replace('/', '\\')

        self.device = None              # 设备
        self.currentDateTime = None     # 当前时间

        self.snapThread = None          # 拍照线程      
        self.upDataImage = None         # 更新图片
        self.pixelFormat = None         # 像素格式
        self.Height = 0                 # 图像高度                 
        self.Width = 0                  # 图像宽度
        
        self.viewThread = None          # 预览线程
        
        self.imgName = None             # 读取文件夹的图像[np.ndarray]
        
        self.imageViewThread = None     # 读取RGGB通道预览线程

        
        self.setWindowTitle("视频预览和捕获")
        self.setStyleSheet("QWidget{background: rgb(255, 255, 255)}")
        # self.setFixedSize(1600, 680)
        self.setui()

    def setui(self):
        buttonQss = """
                QPushButton {
                            font: 11pt  "华文宋体";
                            backgroud-color: rgb(248, 248, 248);
                            border: 1px solid rgb(199, 199, 199);
                            border-radius: 4px;
                            }
                QPushButton:hover {    /* 鼠标悬浮在QPushButton上时的状态 */
                            background-color: rgb(231, 230, 230);
                            border-color:rgb(199, 199, 199);
                            }
                QPushButton:pressed{ 
                            background-color: rgb(255, 255, 255);
                            border-color:rgb(199, 199, 199);
				            }"""
        editQss = """
                        QLineEdit {
                                    font: 11pt  "Consolas";
                                    backgroud-color: rgb(248, 248, 248);
                                    border: 1px solid ;
                                    border-radius: 4px;
                                    }
                    """
        sliderQss = """QSlider::groove:horizontal {border: 0px solid #bbb;}

                        /*1.滑动过的槽设计参数*/
                        QSlider::sub-page:horizontal{
                                    background: rgb(90,49,255); /*槽颜色*/
                                    border-radius: 2px; /*外环区域倒圆角度*/
                                    margin-top:8px; /*上遮住区域高度*/  
                                    margin-bottom:8px;  /*下遮住区域高度*/ }

                        /*2.未滑动过的槽设计参数*/
                        QSlider::add-page:horizontal {
                                    background: rgb(250, 250, 250);  /*槽颜色*/
                                    border: 0px solid #777; /*外环大小0px就是不显示，默认也是0*/
                                    border-radius: 2px; /*外环区域倒圆角度*/
                                    margin-top:9px; /*上遮住区域高度*/
                                    margin-bottom:9px;  /*下遮住区域高度*/}

                        /*3.平时滑动的滑块设计参数*/
                        QSlider::handle:horizontal {
                                    background: rgb(193,204,208);   /*滑块颜色*/
                                    width: 5px; /*滑块的宽度*/
                                    border: 1px solid rgb(193,204,208); /*滑块外环为1px，再加颜色*/
                                    border-radius: 2px; /*滑块外环倒圆角度*/
                                    margin-top:6px; /*上遮住区域高度*/
                                    margin-bottom:6px;  /*下遮住区域高度*/}

                        /*4.手动拉动时显示的滑块设计参数*/
                        QSlider::handle:horizontal:hover {
                            background: rgb(193,204,208);   /*滑块颜色*/
                            width: 10px;    /*滑块的宽度*/
                            border: 1px solid rgb(193,204,208); /*滑块外环为1px，再加颜色*/
                            border-radius: 5px; /*滑块外环倒圆角度*/ 
                            margin-top:4px; /*上遮住区域高度*/
                            margin-bottom:4px;  /*下遮住区域高度*/}
                    """
        comboQss = """QComboBox {
                                font: 9pt "Consolas";
                                border-radius: 3px;
                                border:1px solid rgb(0, 0, 0);}
                      QComboBox:hover {
                                /* 鼠标悬浮在QComboBox上时的状态 */
                                background-color: rgb(255, 255, 255);
                                border:1px solid rgb(0, 0, 0);
                                color: black;}
                      /* 下拉列表里的颜色 */
                      QComboBox QAbstractItemView {
                                border: 1px solid rgb(0, 0, 0);/*边框宽度、线形、颜色*/
                                border-radius: 1px;/*圆角*/
                                min-width: 2em;   /*# 组合框的最小宽度*/
                                padding: 1px 2px 1px 2px;  /*针对于组合框中的文本内容*/
                                selection-color: rgb(255, 255, 255);
                                selection-background-color: rgb(72, 156, 236);
                                background-color: rgb(255, 255, 255);/*背景颜色*/}"""
        groupQss = """QGroupBox{
                                border: 2px solid rgb(220, 220, 220);
                                border-radius:5px;
                                margin-top:3ex;
                                font-family:宋体;
                                font: 20px; }
                    QGroupBox::title{
                                subcontrol-origin:margin;
                                subcontrol-position:top left;
                                padding:0 3px;}"""
        
        self.allLayout.addLayout(self.leftLayout)
        # 设备
        self.deviceGroup.setStyleSheet(groupQss)
        self.leftLayout.addWidget(self.deviceGroup)
        
        self.deviceGroup.setLayout(self.deviceLayout)
        self.deviceGroup.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        openSpacer = QSpacerItem(39, 5, QSizePolicy.Expanding, QSizePolicy.Fixed)  # 弹簧
        self.deviceLayout.addSpacerItem(openSpacer)
        # 连接相机
        self.connectCameraButton.setFixedWidth(45)
        self.connectCameraButton.setFixedHeight(35)
        self.connectCameraButton.setStyleSheet(buttonQss)
        self.deviceLayout.addWidget(self.connectCameraButton)
        # 打开相机
        self.openButton.setFixedWidth(50)
        self.openButton.setFixedHeight(35)
        self.openButton.setStyleSheet(buttonQss)
        self.deviceLayout.addWidget(self.openButton)
        # 关闭相机
        self.closeButton.setFixedWidth(50)
        self.closeButton.setFixedHeight(35)
        self.closeButton.setCheckable(True)
        self.closeButton.setStyleSheet(buttonQss)
        self.deviceLayout.addWidget(self.closeButton)
        # 返回
        self.returnButton.setFixedWidth(45)
        self.returnButton.setFixedHeight(35)
        self.returnButton.setCheckable(True)
        self.returnButton.setStyleSheet(buttonQss)
        self.deviceLayout.addWidget(self.returnButton)

        returnSpacer = QSpacerItem(39, 5, QSizePolicy.Expanding, QSizePolicy.Fixed)  # 弹簧
        self.deviceLayout.addSpacerItem(returnSpacer)

        # 像素格式
        self.imgGroup.setEnabled(False)
        self.imgGroup.setStyleSheet(groupQss)
        self.leftLayout.addWidget(self.imgGroup)
        self.imgGroup.setLayout(self.imgLayout)
        self.imgGroup.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        # 格式
        self.formatLabel.setFixedWidth(51)
        self.formatLabel.setFixedHeight(40)
        self.formatLabel.setStyleSheet("""QLabel{font: 11pt "华文宋体";}""")
        self.imgLayout.addWidget(self.formatLabel, 0, 0, 1, 1)

        enumentries = ['PolarizedAngles_0d_45d_90d_135d_BayerRG8', 'PolarizedStokes_S0_S1_S2_S3_BayerRG8',
                       'PolarizedDolpAolp_BayerRG8', 'PolarizedDolpAolp_BayerRG12p', 'PolarizedDolp_BayerRG8',
                       'PolarizedDolp_BayerRG12p', 'PolarizedAolp_BayerRG8', 'PolarizedAolp_BayerRG12p',
                       'PolarizedDolpAngle_BayerRG8', 'PolarizedDolpAngle_BayerRG12p', 'PolarizedDolpAngle_BayerRG16']
        
        self.formatEdit.addItems(enumentries)
        self.formatEdit.setFixedWidth(230)
        self.formatEdit.setFixedHeight(40)
        self.formatEdit.setStyleSheet(comboQss)
        self.imgLayout.addWidget(self.formatEdit, 0, 1, 1, 1)
        # 分辨率
        self.pixelLabel.setFixedWidth(51)
        self.pixelLabel.setFixedHeight(40)
        self.pixelLabel.setStyleSheet("""QLabel{font: 11pt "华文宋体";}""")
        self.imgLayout.addWidget(self.pixelLabel, 1, 0, 1, 1)
        
        pixel = ['1224*1024', '2448*2048']
        self.pixelEdit.addItems(pixel)
        self.pixelEdit.setFixedWidth(230)
        self.pixelEdit.setFixedHeight(32)
        self.pixelEdit.setStyleSheet(comboQss)
        self.imgLayout.addWidget(self.pixelEdit, 1, 1, 1, 1)

        # 相机参数设置
        self.paramGroup.setEnabled(False)
        self.paramGroup.setStyleSheet(groupQss)
        self.leftLayout.addWidget(self.paramGroup)
        self.paramGroup.setLayout(self.paramLayout)
        self.paramGroup.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        # 曝光
        self.expLabel.setFixedWidth(30)
        self.expLabel.setFixedHeight(32)
        self.expLabel.setStyleSheet("""QLabel{font: 11pt "华文宋体";}""")
        self.expLayout.addWidget(self.expLabel)
        self.expEdit.setEnabled(False)
        self.expEdit.setFixedWidth(70)
        self.expEdit.setFixedHeight(32)
        self.expEdit.setStyleSheet("""QLineEdit{font: 9pt "Consolas";}""")
        self.expLayout.addWidget(self.expEdit)

        self.usLabel.setFixedWidth(32)
        self.usLabel.setFixedHeight(32)
        self.usLabel.setStyleSheet("""QLabel{font: 9pt "Consolas";}""")
        self.expLayout.addWidget(self.usLabel)

        self.expTip.setFixedWidth(125)
        self.expTip.setFixedHeight(32)
        self.expTip.setStyleSheet("""QLabel{font: 9pt "Consolas";}""")
        self.expLayout.addWidget(self.expTip)

        expSpacer = QSpacerItem(10, 5, QSizePolicy.Expanding, QSizePolicy.Fixed)  # 弹簧
        self.expLayout.addSpacerItem(expSpacer)

        self.paramLayout.addLayout(self.expLayout)

        self.sliderExpo.setEnabled(False)
        self.sliderExpo.setRange(33456, 44831200)
        self.sliderExpo.setPageStep(1)
        self.sliderExpo.setStyleSheet(sliderQss)
        self.sliderExpLayout.addWidget(self.sliderExpo)

        self.expCheckButton.setChecked(True)
        self.expCheckButton.setFixedWidth(52)
        self.expCheckButton.setFixedHeight(20)
        self.sliderExpLayout.addWidget(self.expCheckButton)
        self.paramLayout.addLayout(self.sliderExpLayout)
        # 帧率
        self.fpsLabel.setFixedWidth(32)
        self.fpsLabel.setFixedHeight(32)
        self.fpsLabel.setStyleSheet("""QLabel{font: 11pt "华文宋体";}""")
        self.fpsLayout.addWidget(self.fpsLabel)

        self.fpsEdit.setEnabled(False)
        self.fpsEdit.setFixedHeight(32)
        self.fpsEdit.setFixedWidth(110)
        self.fpsEdit.setStyleSheet("""QLineEdit{font: 9pt "Consolas";}""")
        self.fpsLayout.addWidget(self.fpsEdit)

        fpsSpacer = QSpacerItem(0, 5, QSizePolicy.Expanding, QSizePolicy.Fixed)  # 弹簧
        self.fpsLayout.addSpacerItem(fpsSpacer)

        self.paramLayout.addLayout(self.fpsLayout)

        self.sliderFps.setRange(10, 2221)
        self.sliderFps.setPageStep(1)
        self.sliderFps.setEnabled(False)
        self.sliderFps.setStyleSheet(sliderQss)
        self.sliderFpsLayout.addWidget(self.sliderFps)

        self.fpsCheckButton.setChecked(True)
        self.fpsCheckButton.setFixedWidth(52)
        self.fpsCheckButton.setFixedHeight(20)
        self.sliderFpsLayout.addWidget(self.fpsCheckButton)
        self.paramLayout.addLayout(self.sliderFpsLayout)
        # 增益
        self.gainLabel.setFixedWidth(32)
        self.gainLabel.setFixedHeight(32)
        self.gainLabel.setStyleSheet("""QLabel{font: 11pt "华文宋体";}""")
        self.gainLayout.addWidget(self.gainLabel)

        self.gainEdit.setEnabled(False)
        self.gainEdit.setFixedHeight(32)
        self.gainEdit.setFixedWidth(110)
        self.gainEdit.setStyleSheet("""QLineEdit{font: 9pt "Consolas";}""")
        self.gainLayout.addWidget(self.gainEdit)

        gainSpacer = QSpacerItem(0, 5, QSizePolicy.Expanding, QSizePolicy.Fixed)  # 弹簧
        self.gainLayout.addSpacerItem(gainSpacer)

        self.paramLayout.addLayout(self.gainLayout)

        self.sliderGain.setEnabled(False)
        self.sliderGain.setRange(0, 48000)
        self.sliderGain.setPageStep(1)
        self.sliderGain.setStyleSheet(sliderQss)
        self.sliderGainLayout.addWidget(self.sliderGain)

        self.gainCheckButton.setChecked(True)
        self.gainCheckButton.setFixedWidth(52)
        self.gainCheckButton.setFixedHeight(20)
        self.sliderGainLayout.addWidget(self.gainCheckButton)
        self.paramLayout.addLayout(self.sliderGainLayout)
        # 白平衡
        self.balanceWhiteLabel.setFixedWidth(52)
        self.balanceWhiteLabel.setFixedHeight(32)
        self.balanceWhiteLabel.setStyleSheet("""QLabel{font: 11pt "华文宋体";}""")
        self.balanceWhiteLayout.addWidget(self.balanceWhiteLabel)

        items = ['off', 'Once', 'Continuous']
        self.balanceWhiteCombox.addItems(items)
        self.balanceWhiteCombox.setCurrentIndex(2)
        self.balanceWhiteCombox.setFixedHeight(32)
        self.balanceWhiteCombox.setFixedWidth(230)
        self.balanceWhiteCombox.setStyleSheet(comboQss)
        self.balanceWhiteLayout.addWidget(self.balanceWhiteCombox)

        balanceWhiteSpacer = QSpacerItem(0, 5, QSizePolicy.Expanding, QSizePolicy.Fixed)  # 弹簧
        self.balanceWhiteLayout.addSpacerItem(balanceWhiteSpacer)

        self.paramLayout.addLayout(self.balanceWhiteLayout)
        # 图像捕捉
        self.imgSnapGroup.setEnabled(False)
        self.imgSnapGroup.setStyleSheet(groupQss)
        self.leftLayout.addWidget(self.imgSnapGroup)
        self.imgSnapGroup.setLayout(self.imgSnapLayout)
        self.imgSnapGroup.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        # 地址
        self.pathLabel.setFixedWidth(28)
        self.pathLabel.setFixedHeight(32)
        self.pathLabel.setStyleSheet("""QLabel{font: 11pt "华文宋体";}""")
        self.pathLayout.addWidget(self.pathLabel)
        self.pathEdit.setFixedWidth(220)
        self.pathEdit.setFixedHeight(32)
        self.pathEdit.setStyleSheet("""QLineEdit{border: 0px solid rgb(255, 255, 255);
                                                    font: 9pt "Consolas";}""")
        self.pathLayout.addWidget(self.pathEdit)
        # 打开地址按钮
        self.openFileButton.setFixedWidth(30)
        self.openFileButton.setChecked(True)
        self.openFileButton.setStyleSheet(buttonQss)
        self.pathLayout.addWidget(self.openFileButton)
        self.imgSnapLayout.addLayout(self.pathLayout)
        # 捕获图像按钮
        self.snapButton.setCheckable(True)
        self.snapButton.setFixedWidth(85)
        self.snapButton.setFixedHeight(35)
        self.snapButton.setStyleSheet(buttonQss)
        self.buttonLayout.addWidget(self.snapButton)
        # 录制视频按钮
        self.recorderButton.setFixedWidth(85)
        self.recorderButton.setFixedHeight(35)
        self.recorderButton.setCheckable(True)
        self.recorderButton.setStyleSheet(buttonQss)
        self.buttonLayout.addWidget(self.recorderButton)
        # 停止录制视频按钮
        self.endButton.setFixedWidth(85)
        self.endButton.setFixedHeight(35)
        self.endButton.setCheckable(True)
        self.endButton.setStyleSheet(buttonQss)
        self.buttonLayout.addWidget(self.endButton)
        self.imgSnapLayout.addLayout(self.buttonLayout)
        # 限制
        self.limitLabel.setStyleSheet("""QLabel{font: 11pt "华文宋体";}""")
        self.limitLayout.addWidget(self.limitLabel)
        limit = ['无限制', '10s', '30s', '60s', '120s', '180s', '1frames', '10frames', '50frames',
                 '100frames', '1000frames', '2000frames', '3000frames']
        self.limitEdit.addItems(limit)
        self.limitEdit.setFixedWidth(220)
        self.limitEdit.setFixedHeight(32)
        self.limitEdit.setStyleSheet(comboQss)
        self.limitLayout.addWidget(self.limitEdit)
        self.imgSnapLayout.addLayout(self.limitLayout)
        # 计划拍摄按钮
        self.planeButton.setFixedWidth(140)
        self.planeButton.setFixedHeight(40)
        self.planeButton.setCheckable(True)
        self.planeButton.setStyleSheet(buttonQss)
        self.planeButtonLayout.addWidget(self.planeButton)
        # 停止计划捕获按钮
        self.planeStopButton.setCheckable(True)
        self.planeStopButton.setFixedWidth(140)
        self.planeStopButton.setFixedHeight(40)
        self.planeStopButton.setStyleSheet(buttonQss)
        self.planeButtonLayout.addWidget(self.planeStopButton)
        self.imgSnapLayout.addLayout(self.planeButtonLayout)

        self.groupBox.setStyleSheet(groupQss)
        self.allLayout.addWidget(self.groupBox)

        self.gropboxlayouth.setAlignment(Qt.AlignCenter)
        self.groupBox.setLayout(self.gropboxlayouth)

        self.tips.setAlignment(Qt.AlignCenter)
        self.gropboxlayouth.addWidget(self.tips)

        self.groupLayout.setAlignment(Qt.AlignCenter)
        # self.groupBox.setLayout(self.groupLayout)
        self.gropboxlayouth.addLayout(self.groupLayout)
        self.groupBox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.viewLabel.setFixedWidth(612)
        self.viewLabel.setFixedHeight(512)
        self.viewLabel.setStyleSheet("""QLabel{background-color:rgb(255, 255, 255);}""")
        self.groupLayout.addWidget(self.viewLabel, 0, 0, 2, 2)

        self.linewidget.setFixedWidth(1)
        self.linewidget.setFixedHeight(512)
        self.groupLayout.addWidget(self.linewidget, 0, 2, 1, 2)

        self.view_RGGB.setFixedWidth(612)
        self.view_RGGB.setFixedHeight(512)
        self.view_RGGB.setStyleSheet("""QLabel{background-color:rgb(250, 250, 250);}""")
        self.groupLayout.addWidget(self.view_RGGB, 0, 3, 2, 2)

        self.chooseDir.setStyleSheet(editQss)
        self.chooseDir.setFixedHeight(36)
        self.groupLayout.addWidget(self.chooseDir, 2, 0, 1, 4)
        self.chooseRaw.setFixedWidth(140)
        self.chooseRaw.setFixedHeight(40)
        self.chooseRaw.setCheckable(True)
        self.chooseRaw.setStyleSheet(buttonQss)
        self.groupLayout.addWidget(self.chooseRaw, 2, 4, 1, 1)



        # ---------------------------滑块控件------------------------------
        self.expEdit.editingFinished.connect(self.expEditChanged)
        self.sliderExpo.valueChanged.connect(self.expSliderChanged)
        self.expCheckButton.stateChanged.connect(self.expCheckStatus)

        self.fpsEdit.editingFinished.connect(self.fpsEditChanged)
        self.sliderFps.valueChanged.connect(self.fpsSliderChanged)
        self.fpsCheckButton.stateChanged.connect(self.fpsCheckStatus)

        self.gainEdit.editingFinished.connect(self.gainEditChanged)
        self.sliderGain.valueChanged.connect(self.gainSliderChanged)
        self.gainCheckButton.stateChanged.connect(self.gainCheckStatus)
        # -----------------------------开关相机-------------------------------
        self.connectCameraButton.clicked.connect(self.ConnectSlot)  # 连接相机及相机状态的设置
        self.openButton.clicked.connect(self.openView)  # 开启预览
        self.closeButton.clicked.connect(self.closeView)    # 关闭预览
        # ----------------------------打开本地地址------------------------------
        self.openFileButton.clicked.connect(self.openFile)
        # ------------------------------单次拍照-------------------------------
        self.snapButton.clicked.connect(self.snapPicture)
        # ------------------------------计划拍照-------------------------------
        self.planeButton.clicked.connect(self.planeSnapPicture)
        self.planeStopButton.clicked.connect(self.planeStopPicture)
        # -----------------------------界面跳转信号-----------------------------
        self.returnButton.clicked.connect(self.Initial_signal)

        self.chooseRaw.clicked.connect(self.chooseLocalRaw)
        
        
    # --------------------------------曝光包含的控件设置-----------------------------------
    def expEditChanged(self):
        exp = self.expEdit.text()
        self.sliderExpo.setSliderPosition(int(float(exp) * 1000))
    def expSliderChanged(self):
        value = self.sliderExpo.value()
        self.expEdit.setText(str(value / 1000))
    def expCheckStatus(self):
        if self.expCheckButton.isChecked():
            self.sliderExpo.setEnabled(False)
            self.expEdit.setEnabled(False)
            self.expEdit.setText('44831.2')
            self.sliderExpo.setSliderPosition(int(float(self.expEdit.text()) * 1000))

        else:
            self.sliderExpo.setEnabled(True)
            self.expEdit.setEnabled(True)
    # --------------------------------帧率包含的控件设置-----------------------------------
    def fpsEditChanged(self):
        fps = self.fpsEdit.text()
        self.sliderFps.setSliderPosition(int(float(fps) * 100))
    def fpsSliderChanged(self):
        value = self.sliderFps.value()
        self.fpsEdit.setText(str(value / 100))
    def fpsCheckStatus(self):
        if self.fpsCheckButton.isChecked():
            self.sliderFps.setEnabled(False)
            self.fpsEdit.setEnabled(False)
            self.fpsEdit.setText('22.21')
            self.sliderFps.setSliderPosition(int(float(self.fpsEdit.text()) * 100))

        else:
            self.sliderFps.setEnabled(True)
            self.fpsEdit.setEnabled(True)
    # --------------------------------增益包含的控件设置------------------------------------
    def gainEditChanged(self):
        gain = self.gainEdit.text()
        self.sliderGain.setSliderPosition(int(float(gain) * 1000))
    def gainSliderChanged(self):
        value = self.sliderGain.value()
        self.gainEdit.setText(str(value / 1000))
    def gainCheckStatus(self):
        if self.gainCheckButton.isChecked():
            self.sliderGain.setEnabled(False)
            self.gainEdit.setEnabled(False)
            self.gainEdit.setText('15')
            self.sliderGain.setSliderPosition(int(float(self.gainEdit.text()) * 1000))
        else:
            self.sliderGain.setEnabled(True)
            self.gainEdit.setEnabled(True)
    # -------------------------------连接相机并初始化设置-----------------------------------
    def findDevice(self):
        device = None

        devices = Device_Find().findDivice()
        device = devices[0]
        if device is None:
            QMessageBox.warning(self, "错误提示", "请连接设备后再打开")
        else:
            self.imgGroup.setEnabled(True)
            self.paramGroup.setEnabled(True)
            self.imgSnapGroup.setEnabled(False)
        return device
    def ConnectSlot(self):
        self.device = self.findDevice()
    # ----------------------------------相机视频流预览--------------------------------------
    # -----------开启预览-----------
    def openView(self):
        self.imgGroup.setEnabled(False)
        self.paramGroup.setEnabled(False)
        self.imgSnapGroup.setEnabled(True)
        self.pixelFormat = self.formatEdit.currentText()  # 获取像素格式
        
        nodemap = self.device.nodemap
        nodes = nodemap.get_node(['Width', 'Height', 'PixelFormat',
                                  'ExposureAuto', 'ExposureTime',
                                  'AcquisitionFrameRate', 'AcquisitionFrameRateEnable',
                                  'GainAuto', 'GainSelector', 'Gain',
                                  'BalanceWhiteAuto', 'BalanceWhiteEnable'])

        nodes['Width'].value = nodes['Width'].max
        nodes['Height'].value = nodes['Height'].max
        nodes['PixelFormat'].value = self.pixelFormat  # 黑白[Channels:1]   也可设置为彩色: RGB8 -->Channels:3

        # 曝光
        if self.expCheckButton.isChecked():
            nodes['ExposureAuto'].value = 'Continuous'
            expourse_time = nodes['ExposureTime'].value
            self.expEdit.setText(str(expourse_time))
            self.sliderExpo.setSliderPosition(int(expourse_time * 1000))
        else:
            nodes['ExposureAuto'].value = 'Off'
            nodes['ExposureTime'].value = float(self.expEdit.text())
        # 帧率
        if self.fpsCheckButton.isChecked():
            nodes['AcquisitionFrameRateEnable'] = False
            fps_value = round(nodes['AcquisitionFrameRate'].value, 3)
            self.fpsEdit.setText(str(fps_value))
            self.sliderFps.setSliderPosition(int(fps_value * 100))
        else:
            nodes['AcquisitionFrameRateEnable'] = True
            nodes['AcquisitionFrameRate'].value = float(self.fpsEdit.text())
        # 增益
        if self.gainCheckButton.isChecked():
            nodes['GainAuto'].value = 'Continuous'
            gain = nodes['Gain'].value
            self.gainEdit.setText(str(gain))
            self.sliderGain.setSliderPosition(int(gain * 1000))
        else:
            nodes['GainAuto'].value = 'Off'
            nodes['Gain'].value = float(self.gainEdit.text())

        # 获取图像分辨率,并设置分辨率下拉栏
        if nodes['Width'].value == 1024:
            self.pixelEdit.setCurrentIndex(0)
        else:
            self.pixelEdit.setCurrentIndex(1)

        tl_stream_nodemap = self.device.tl_stream_nodemap
        tl_stream_nodemap["StreamBufferHandlingMode"].value = "NewestOnly"  # 设置传输流的属性
        tl_stream_nodemap['StreamAutoNegotiatePacketSize'].value = True
        tl_stream_nodemap['StreamPacketResendEnable'].value = True
        # add Thread
        self.viewThread = ViewThread(self.device, self.viewLabel)
        self.viewThread.start()


        '''
        # 提取绿色通道
        self.green_even_data = np.zeros_like(reshapeImage)
        self.green_even_data[::2, 1::2] = reshapeImage[::2, 1::2]
        self.green_even_data[1::2, ::2] = reshapeImage[1::2, ::2]

        self.green_odd_data = np.zeros_like(reshapeImage)
        self.green_odd_data[1::2, 1::2] = reshapeImage[1::2, 1::2]
        # 提取蓝色通道
        self.blue_data = np.zeros_like(reshapeImage)
        self.blue_data[1::2, ::2] = reshapeImage[1::2, ::2]
        '''
    # -----------关闭预览-----------
    def closeView(self):
        if self.viewThread.isRunning():
            self.viewThread.stop()
        self.imgGroup.setEnabled(True)
        self.paramGroup.setEnabled(True)
        self.imgSnapGroup.setEnabled(False)
    # ----------------------------------打开本地文件夹---------------------------------------
    def openFile(self):
        self.pathEdit.clear()
        chooseDir = QFileDialog.getExistingDirectory(self, "本地文件", "C:/")
        self.pathEdit.setText(str(chooseDir))
        path = self.pathEdit.text()
        if path == '':
            self.pathEdit.setText(self.cur_path_str)
    # ------------------------------------捕获图片-------------------------------------------
    def snapPicture(self):
        rawimg = self.viewThread.read_img
        self.currentDateTime = QDateTime.currentDateTime().toString("yyyy-MM-dd HH-mm-ss")  # 时间
        name = self.pixelFormat + '_' + self.currentDateTime  # 图片名字
        saveFormat = '.raw'  # 保存格式
        if self.pathEdit.text() == '':
            path = self.cur_path_str
        else:
            path = self.pathEdit.text()
        Folder = path + '/' + self.pixelFormat
        if not os.path.exists(Folder):
            os.makedirs(Folder)
        save_dir = Folder + '/' + name + saveFormat  # 完整的保存路径及名字格式
        rawimg.tofile(save_dir)  # 保存到本地

        self.chooseDir.setText(save_dir)
    # ------------------------------------计划捕获-------------------------------------------
    # -----------开启计划捕获-----------
    def planeSnapPicture(self):
        limitStyle = self.limitEdit.currentIndex()
        if self.pathEdit.text() == '':
            path = self.cur_path_str
        else:
            path = self.pathEdit.text()
        self.snapThread = SnapThread(self.device, self.raw_image, path, limitStyle)
        self.viewThread.RawImage.connect(self.updata_RawData)
        self.snapThread.start()
    # 更新图像从ImageThread线程到主线程，通过主线程转到SnapThread线程
    def updata_RawData(self, rawData):
        self.upDataImage = rawData
        print(f'upDataImage again send to snapThread')
        self.snapThread.data = self.upDataImage
    # -----------关闭计划捕获-----------
    def planeStopPicture(self):
        if self.snapThread.isRunning():
            self.snapThread.stop()
            self.viewThread.RawImage.disconnect(self.updata_RawData)
    # ---------------------------------选择本地图片进行预览------------------------------------
    def chooseLocalRaw(self):
        if self.chooseDir.text() != '' and self.pathEdit.text() != '':
            self.imgName = self.chooseDir.text()
            self.chooseDir.clear()
            print(f'self.chooseEdit.text is :{self.chooseDir.text()}')
        else:
            self.imgName, imgType = QFileDialog.getOpenFileName(self, "打开图片", "",
                                                            "*All Files(*);;BMP(*.raw)")
            self.chooseDir.setText(self.imgName)
        if self.imgName != '':
            self.imageViewThread = viewOnlyChannelThread(self.imgName, self.fig1, self.view_RGGB)
            self.imageViewThread.start()
        else:
            print(f'Not image had choosed!')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    acquireImage = LiveORSnap()
    acquireImage.show()
    exit(app.exec_())

